package com.problem;

/**
 * https://leetcode-cn.com/problems/reverse-linked-list/
 */
public class ReverseList2 {

    /**
     * 示例:
     *
     * 输入: 1->2->3->4->5->NULL
     * 输出: 5->4->3->2->1->NULL
     * 递归解决
     * @param head
     * @return
     */
    public static ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return  head;
        }
        ListNode current = head.next;
        head.next = null;
        ListNode prev = head;
        ListNode next = null;
        while (current != null) {
           // ListNode next = head;
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        return prev;
    }


    public void revert(ListNode node) {
        if (node.next == null) {
            return;
        }
    }

    public static void print(ListNode listNode) {
        if (listNode != null) {
            System.out.println(listNode.val);
        } else{
            System.out.println("null");
            return;
        }
        if (listNode.next != null) {

            print(listNode.next);
        }
    }
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode1.next=listNode2;
        listNode2.next = listNode3;listNode3.next=listNode4;listNode4.next = listNode5;

       ListNode listNode = reverseList(listNode1);
        print(listNode);
    }



    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        ListNode(int x, ListNode next) {
            val = x;
            this.next = next;
        }
    }
}
